package com.hybao.service.login;

import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

import javax.servlet.http.HttpServletResponse;

import com.hybao.pojo.dao.LoginInfoDao;
import com.hybao.pojo.dao.UserInfoDao;
import com.hybao.pojo.ormaaping.UserInfo;
import com.hybao.security.AuthHandler;
import com.hybao.topApi.UserTopService;
import com.taobao.api.domain.User;

public class LoginService {
	private UserInfoDao userInfoDao;
	private LoginInfoDao loginInfoDao;
	private UserTopService userTopService;
	
	public boolean checkLogin(String userName,String passwd){
		int int_res = userInfoDao.getUserCountWithNameAndPwd(userName, passwd);
		if(int_res > 0){
			return true;
		}
		return false;
	}
	
	public boolean chenckUser(String nick,String topSession,HttpServletResponse response){
		UserInfo userInfo = userInfoDao.getUserInfoWithNick(nick);
		String userId = null;
		if(userInfo == null){
			User user = userTopService.getUserFromTopWithNick(nick,topSession);
			if(user == null){
				return false;
			}
			//新建用户
			Map<String,String> userInfoMap = new HashMap<String,String>();
			userId = UUID.randomUUID().toString();
			SimpleDateFormat dateformat=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			userInfoMap.put("userName", user.getNick());
			userInfoMap.put("phone", "");
			if(user.getBirthday() == null){
				userInfoMap.put("birth", null);
			}
			else{
				userInfoMap.put("birth", dateformat.format(user.getBirthday()));
			}
			userInfoMap.put("userEmail", user.getEmail());
			userInfoMap.put("userId", userId);
			userInfoDao.createUserInfo(userInfoMap);
			//创建日志
			loginInfoDao.insertLoginInfo(userId, topSession);
		}
		else{
			userId = userInfo.getUid();
			loginInfoDao.updateLoginInfo(userInfo.getUid());
		}
		//write cookie
		AuthHandler.setUserIntoCookie(response, userId, nick);
		return true;
		
	}
	
	public void createUserInfo(Map<String,String> userInfoMap){
		userInfoDao.createUserInfo(userInfoMap);
	}
	
	//---- getter and setter --
	public UserInfoDao getUserInfoDao() {
		return userInfoDao;
	}
	public void setUserInfoDao(UserInfoDao userInfoDao) {
		this.userInfoDao = userInfoDao;
	}
	public UserTopService getUserTopService() {
		return userTopService;
	}
	public void setUserTopService(UserTopService userTopService) {
		this.userTopService = userTopService;
	}
	public LoginInfoDao getLoginInfoDao() {
		return loginInfoDao;
	}
	public void setLoginInfoDao(LoginInfoDao loginInfoDao) {
		this.loginInfoDao = loginInfoDao;
	}
}
